// import { getPrintContentForPc, findShopTemplate } from '@/api'
import { getPrintContentForPc } from '../components/api'
import { getLodop } from "@/utils/LodopFuncs.js";
import { Notification } from 'element-ui';
const io = require("socket.io-client");

var pushBasePath = "http://192.168.1.103:8084/push";
var pushBasePath = "http://192.168.1.234:8092/push";
// var pushBasePath = "https://www.madiancan.com/push";
// var pushBasePath = "https://mdc.zuwo.la/push";
const basePath = "https://www.madiancan.com/"
var chatSocket = io.connect(pushBasePath);
console.log(chatSocket)

function pushConnect() {
    console.log('链接');
    var jsonObject = {
        userId: localStorage.shopId,
        sessionId: localStorage.shopId
    };
    console.log(chatSocket.json.send(jsonObject))
    chatSocket.json.send(jsonObject);
}
chatSocket.on('connect', function() {
    pushConnect();
});

chatSocket.on('disconnect', function() {
    console.log('disconnect')
});


chatSocket.on('error', function() {
    console.log('error')
});

function sendDisconnect() {
    chatSocket.disconnect();
}
//转换下属性名
function changeBean(bean) {
    var newBean = {
        createTime: bean.createTime,
        number: bean.tradeNo,
        peopleNum: bean.mealsNum,
        orderDetailList: [],
        chPrice: "0.0",
        postPrice: bean.distributionPrice ? bean.distributionPrice : 0.0,
        subDesc: [],
        cardMoney: "0.0",
        payPrice: bean.payMoney,
        customerPhone: bean.buyerPhone,
        customerName: bean.buyerName,
        remark: bean.buyerMark,
        shopName: bean.shopName,
        model: bean.orderCategory == 3 ? 0 : 1,
        customerAddr: bean.buyerAddress,
        orderNum: bean.orderNum,
        printTempType: bean.printTempType,
    }
    var foodBoxPrice = 0;
    var products = (bean.products);
    for (var p in products) {
        newBean.orderDetailList.push({
                name: products[p].goodsName,
                price: products[p].turnoverPrice,
                specStr: products[p].specDesc,
                quantity: products[p].buyCount,
                goodsCategory: products[p].goodsCategory,
                productSaleStatus: products[p].productSaleStatus,

            })
            //累加餐盒费
        foodBoxPrice += (products[p].foodBoxPrice ? products[p].foodBoxPrice : 0) * products[p].buyCount;
    }
    newBean.chPrice = foodBoxPrice.toFixed(1);;
    return newBean;
}

//转换成html
function newChangeBean(bean) {
    var html = "";
    $(bean).each(function(index, bean) {
        var style_str = ""; //    text-align: center;
        if (bean.alignType == 1) { // 1 左对齐 2 中间对其 3右对齐
            style_str += " text-align: left;";
        } else if (bean.alignType == 2) {
            style_str += " text-align: center;";
        } else if (bean.alignType == 3) {
            style_str += " text-align: right;";
        }
        if (bean.isbold == 1) { //  是否加粗  1是  2 不加粗
            style_str += "font-weight:bold;";
        }
        if (bean.isItalic == 1) { //  是否倾斜 1是 2 不倾斜
            style_str += "font-style: italic;";
        }
        if (bean.txtSizeType == 1) { //字体大小 1 小 2中 3 大
            style_str += "font-size: 11px;";
        } else if (bean.txtSizeType == 2) {
            style_str += "font-size:12px;";
        } else if (bean.txtSizeType == 3) {
            style_str += "font-size:17px;";
        }
        style_str += "    padding: 0 10%;";
        console.log(bean.txt.replace("\n", ""));
        html += "<p style='" + style_str + "'>" + bean.txt.replace(new RegExp(" ", "gm"), "-").replace("\n", "<br>") + "</p>";
    });

    return html;
}

chatSocket.on("message", function(data, ackServerCallback) {
    console.log("收到message:" + data);
    if ("" == data) {
        //只播放声音
        // playSound();
    } else {
        var bean = JSON.parse(data);
        //判断订单是否是该商户的
        if (localStorage.shopId != bean.shopId) {
            return false;
        }
        if (bean.noticeType == 2 || bean.noticeType == 1) {
            if (bean.noticeType == 2) {
                Notification({
                    title: "提示",
                    message: bean.buyerAddress + " 的客户 加菜了,请注意处理~",
                    type: "warning",
                    duration: 0
                });
            }
            //播放声音
            playSound();
            //打印订单
            // dayinOrder(bean);

            //用默认的 再打一遍

            //回调
            if (bean.noticeType == 1 && bean.isAutoTake == 1) {
                if (ackServerCallback) {
                    ackServerCallback(bean.mallOrderId);
                }
            }
        } else if (bean.noticeType == 3) { //打印

            getPrintContnet(bean);
        }


    }

});

function getPrintContnet(bean) {
    console.log(bean.printerDevicesId)
        //根据订单id 获取小票信息
    getPrintContentForPc({
        mallOrderId: bean.mallOrderId,
        // groupId: bean.groupId,
        // goodsCategorys: bean.goodsCategorys,
        // printerDevicesId: bean.printerDevicesId
    }).then((data) => {
        if (data.code == 1) {
            newDayinOrder(data.data.htmlContent, bean.deviceIdentifier, bean.pageWidth, bean.printPageNum);
        } else {
            // alert(data.msg);
        }
    })


}

function newDayinOrder(htmlContent, deviceIdentifier, pageWidth, printPageNum) {

    newDayinOrderSub(htmlContent, deviceIdentifier, pageWidth, printPageNum);

}

function dayinOrder(json) {
    var oldValue = JSON.parse(localStorage.getItem("printIndex"));
    if (oldValue) { //循环 打印设备 打印
        for (var o in oldValue) {
            dayinOrderSub(json, oldValue[o].index);
        }
    } else {
        dayinOrderSub(json, -1); //没设置过 就用默认打印机
    }



}

function strlen(str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
        } else {
            len += 2;
        }
    }
    return len;

}

function newDayinOrderSub(htmlContent, printerIndex, pageWidth, printPageNum) {
    //var template_html="<div style='margin-left: -20px'>"+htmlContent+"</div>";
    var template_html = "<div style='margin-left: -20px;padding:20px;'>" + htmlContent + "</div>";
    if (pageWidth == 80) {
        // template_html="<div style='margin-left: 0px'>"+htmlContent+"</div>";
    }
    // console.log(template_html);
    // console.log(pageWidth);
    //  $("#ttt").html(template_html);
    LODOP = getLodop();
    if (!LODOP) {
        if (confirm("打印机连接失败,查看解决方案？")) {
            window.location.href = basePath + "print/tip.html";
        } else {
            return;
        }
    }
    LODOP.PRINT_INIT("订单小票");
    LODOP.ADD_PRINT_HTM(0, 10, "100%", "100%", template_html);
    LODOP.SET_PRINT_COPIES(printPageNum); //设置打印份数
    LODOP.SET_PRINT_PAGESIZE(3, pageWidth * 10, 40, "");
    /* LODOP.PREVIEW();*/
    LODOP.SET_PRINTER_INDEXA(printerIndex);
    LODOP.PRINT();
}

function dayinOrderSub(json, printerIndex) {
    var origin_data = json;
    json = changeBean(json);
    LODOP = getLodop();

    if (!LODOP) {
        if (confirm("打印机连接失败,查看解决方案？")) {
            window.location.href = basePath + "print/tip.html";
        } else {
            return;
        }
    }

    LODOP.PRINT_INIT(json.shopName + "订单小票");
    LODOP.SET_PRINT_STYLE("FontSize", 14);
    LODOP.SET_PRINT_STYLE("Bold", 1);


    if (json.model == 0) {
        var title = "*外卖*";
        var pay_title = "已在线支付";
        var if_show_ch = true;
        var if_show_ship = true;
        var customerName = json.customerName;
        var customerPhone = json.customerPhone;
        var if_show_address = true;
    } else {
        var title = "*堂食*";
        var pay_title = "未支付";
        var if_show_ch = false;
        var if_show_ship = false;
        var customerName = json.customerAddr + "号桌";
        var customerPhone = json.peopleNum + "人用餐";
        var if_show_address = false;
    }

    if (json.printTempType == null || json.printTempType == "") {
        findShopTemplate().then(res => {
            if (res.code == 1) {
                json.printTempType = res.data;
            }
        })
    }
    if (json.printTempType == 2) {
        group_result = json.orderDetailList.reduce(function(h, obj) {
            h[obj.goodsCategory] = (h[obj.goodsCategory] || []).concat(obj);
            return h;
        }, {});
    }

    template_html = "\t<form id=\"form1\">\n" +
        "\t\t<h3 style=\"text-align: center;font-size: 14px;\">" + json.shopName + "</h3>\n" +
        "\t\t<p class=\"split-line\"> <span  class=\"words\">" + pay_title + "</span>   <span class=\"line\" style='float:left'></span>      <span class=\"line\" style='float: right;'></span></p>\n" +
        "\t\t<style>\n" +
        "\n" +
        "\t\t\t.split-line .line{\n" +
        "\t\t\t\twidth: 25%;\n" +
        "\t\t\t\tborder-bottom: 1px solid #ecddeb;margin-top: -9px;\n" +
        "\t\t\t\tdisplay: inline-block;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\t.split-line .words{\n" +
        "\t\t\t\twidth: 100%;\n" +
        "\t\t\t\tdisplay: inline-block;\n" +
        "\t\t\t\ttext-align: center;\n" +
        "\t\t\t\tfont-size: 14px;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\t#form1 {\n" +
        "\t\t\t\ttext-align: left;\n" +
        "\t\t\t\tmax-width: 200px;\n" +
        "\t\t\t\tmargin: auto;\n" +
        "\t\t\t\tpadding: 20px 10px;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\t.section {\n" +
        "\t\t\t\tborder-bottom: 1px solid #ecddeb;\n" +
        "\t\t\t\tpadding-bottom: 8px;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\t.footer span {\n" +
        "\t\t\t\tfloat: right;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\tp {\n" +
        "\t\t\t\tfont-size: 12px;\n" +
        "\t\t\t\tmargin: 8px auto;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\t.large-text {\n" +
        "\t\t\t\tfont-size: 14px;\n" +
        "\t\t\t\tmargin: 10px auto;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\t.phone {\n" +
        "\t\t\t\tmargin-left: 15px;\n" +
        "\t\t\t}\n" +
        "\n" +
        "\t\t\t.payment span {\n" +
        "\t\t\t\tfloat: right;\n" +
        "\t\t\t}\n" +
        "\t\t\t.col-7{\n" +
        "\t\t\t\twidth: 65%;\n" +
        "\t\t\t\tdisplay: inline-block;\n" +
        "\t\t\t}\n" +
        "\t\t\t.col-1{\n" +
        "\t\t\t\twidth: 15%;\n" +
        "\t\t\t\tdisplay: inline-block;\n" +
        "\t\t\t}\n" +
        "\t\t\t.col-2{\n" +
        "\t\t\t\twidth:20%;\n" +
        "\t\t\t\tdisplay: inline-block;\n" +
        "\t\t\t\ttext-align: right;\n" +
        "\t\t\t}\n" +
        "\t\t\t.items{\n" +
        "\t\t\t\tmargin: 8px auto;\n" +
        "\t\t\t\tfont-size: 12px;\n" +
        "\t\t\t}\n" +
        "\t\t</style>\n" +
        "\t\t<div class=\"section\">\n" +
        "\t\t\t<p class=\"large-text\" style=\"margin:20px auto\">" + title + " #" + json.orderNum + "</p>\n" +
        "\t\t\t<p>单号：" + json.number + "</p>\n" +
        "\t\t\t<p>下单时间：" + json.createTime + "</p>\n" +
        "\t\t</div>\n" +
        "\t\t<div class=\"section\">\n" +
        "\t\t\t<div class=\"items\" style=\"margin-bottom:10px;\"><div class=\"col-7\">菜名/规格</div><div class=\"col-1\">数量</div><div class=\"col-2\">小计</div></div>\n" +
        "\n";

    if (json.printTempType == 2) {

        for (var category in group_result) {
            console.log(category);


            var items = group_result[category]


            template_html += "\t\t\t<div class=\"types\">\n" +
                "\t\t\t\t<p class=\"large-text\"  style='font-size:17px;'>" + category + "</p>\n";

            items.forEach((item) => {
                var status_array = ["", "退", "", "换", "赠"];
                template_html += "\t\t\t\t<div class=\"items\"><div class=\"col-7\">" + item.name;
                template_html += status_array[item.productSaleStatus] ? ("<span style='float:right;margin-right:5px'>" + status_array[item.productSaleStatus] + "</span>") : "";
                template_html += "</div><div class=\"col-1\">X" + item.quantity + "</div><div class=\"col-2\">" + item.price + "</div></div>\n";
            });

            template_html += "\t\t\t</div>\n" +
                "\n";
        }


        template_html += "\t\t\t</div>\n";


    } else {
        template_html +=
            "\t\t\t<div class=\"types\">\n";


        json.orderDetailList.forEach((item) => {
            var status_array = ["", "退", "", "换", "赠"];
            template_html += "\t\t\t\t<div class=\"items\"><div class=\"col-7\">" + item.name;
            template_html += status_array[item.productSaleStatus] ? ("<span style='float:right;margin-right:5px'>" + status_array[item.productSaleStatus] + "</span>") : "";
            template_html += "</div><div class=\"col-1\">X" + item.quantity + "</div><div class=\"col-2\">" + item.price + "</div></div>\n";
        });


        template_html += "\t\t\t</div>\n" +
            "\t\t</div>\n";
    }

    template_html += "\t\t<div class=\"section payment\">\n" +
        "\t\t\t<p>总数 <span>" + json.orderDetailList.length + "</span></p>\n" +
        (if_show_ch ? "\t\t\t<p>餐盒费 <span>" + json.chPrice + "</span></p>\n" : "") +
        (if_show_ship ? "\t\t\t<p>配送费 <span>" + json.postPrice + "</span></p>\n" : "") +
        "\t\t\t<p>优惠 <span>" + json.cardMoney + "</span></p>\n" +
        "\t\t\t<p class=\"large-text\">总计<span>" + json.payPrice + "</span></p>\n" +
        "\t\t</div>\n" +
        "\t\t<div class=\"section\">\n" +
        "\t\t\t<p class=\"large-text\">" + customerName + " <span class=\"phone\">" + customerPhone + "</span></p>\n" +

        "\t\t\t<p class=\"large-text\">" + (if_show_address ? json.customerAddr : '') + "</p>\n" +

        "\t\t\t<p>备注: " + ((typeof remark != 'undefined') ? remark : '') + "</p>\n" +
        "\t\t</div>\n" +
        "\t\t<div class=\"footer\">\n" +
        "\t\t\t<p>谢谢惠顾，欢迎下次光临 <span>码点餐#" + origin_data.shopId + "</span></p>\n" +
        "\t\t</div>\n" +
        "\t</form>";



    var printPageSet = JSON.parse(localStorage.getItem("printPageSet"));
    pageWidth = printPageSet ? printPageSet.pageWidth : 580;
    LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", template_html);

    LODOP.SET_PRINT_PAGESIZE(3, pageWidth, 40, "");
    LODOP.PREVIEW();
    /* LODOP.SET_PRINTER_INDEXA(printerIndex);
     LODOP.PRINT();*/
}

function playSound() {
    console.log("playSound");
    // var borswer = window.navigator.userAgent.toLowerCase();
    // if (borswer.indexOf("ie") >= 0) {
    //     //IE内核浏览器
    //     var strEmbed = '<embed name="embedPlay" src="' + basePath + 'js/edcmanage/ding.mp3" autostart="true" hidden="true" loop="false"></embed>';
    //     if ($("#embedPlay").length <= 0)
    //         $("body").append(strEmbed);
    //     var embed = document.embedPlay;

    //     //浏览器不支持 audion，则使用 embed 播放
    //     embed.volume = 100;
    //     //embed.play();这个不需要
    // } else {
    //     //非IE内核浏览器
    //     var strAudio = "<audio id='audioPlay' src='" + basePath + "js/edcmanage/ding.mp3' hidden='true'>";
    //     if ($("#audioPlay").length <= 0)
    //         $("body").append(strAudio);
    //     var audio = document.getElementById("audioPlay");

    //     //浏览器支持 audion
    //     audio.play();
    // }
    let mp3 = `${basePath}js/edcmanage/ding.mp3`;
    let audio = new Audio(mp3);
    audio.play(); //播放 mp3这个音频对象
}

function playNOSound() {
    console.log("playNOSound");
    var borswer = window.navigator.userAgent.toLowerCase();
    if (borswer.indexOf("ie") >= 0) {
        //IE内核浏览器
        var strEmbed = '<embed name="embedPlay2" src="' + basePath + 'js/edcmanage/ding.mp3" autostart="true" hidden="true" loop="false" muted="true"></embed>';
        if ($("#embedPlay2").length <= 0)
            $("body").append(strEmbed);
        var embed = document.embedPlay;

        //浏览器不支持 audion，则使用 embed 播放
        embed.volume = 100;
        //embed.play();这个不需要
    } else {
        //非IE内核浏览器
        var strAudio = "<audio id='audioPlay2' src='" + basePath + "js/edcmanage/ding.mp3' hidden='true' muted=\"true\">";
        if ($("#audioPlay2").length <= 0)
            $("body").append(strAudio);
        var audio = document.getElementById("audioPlay2");

        //浏览器支持 audion
        audio.play();
    }
    if ($("#audioPlay2").length <= 0 && $("#embedPlay2").length <= 0) {
        playNOSound();
        console.log("1111");
    }

}